package forge

import (
	"context"
	"fmt"
	"gomod.alauda.cn/mysql-mgr-operator/pkg/errorx"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/types"
	"satellite/app/option"
	"satellite/pkg/mgrclient"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

type BaseOption struct {
	option.Base
}

type Base struct {
	*BaseOption
}

func NewBase(opt *BaseOption) *Base {
	base := &Base{
		BaseOption: opt,
	}
	return base
}

func (b *Base) getPassword(user string) (string, error) {
	ctx, cancel := context.WithTimeout(context.Background(), b.Timeout)
	defer cancel()
	nn := types.NamespacedName{
		Namespace: b.Namespace,
		Name:      fmt.Sprintf("%v-%v-internal-password", b.Name, user),
	}
	secret := new(corev1.Secret)
	err := mgrclient.Client().Get(ctx, nn, secret)
	if err != nil {
		return "", err
	}
	if password, ok := secret.Data["password"]; ok {
		return string(password), nil
	}
	return "", errorx.PasswordFieldNotFoundErr
}

func (b *Base) getPod(name string) (*corev1.Pod, error) {
	ctx, cancel := context.WithTimeout(context.Background(), b.Timeout)
	defer cancel()
	nn := types.NamespacedName{
		Namespace: b.Namespace,
		Name:      name,
	}
	pod := new(corev1.Pod)
	err := mgrclient.Client().Get(ctx, nn, pod)
	if err != nil {
		return nil, err
	}
	return pod, nil
}

func (b *Base) ListPods(opts ...client.ListOption) (*corev1.PodList, error) {
	ctx, cancel := context.WithTimeout(context.Background(), b.Timeout)
	defer cancel()
	podList := new(corev1.PodList)

	err := mgrclient.Client().List(ctx, podList, opts...)
	if err != nil {
		return nil, err
	}
	return podList, nil
}

func (b *Base) delete(obj client.Object, opt ...client.DeleteOption) error {
	ctx, cancel := context.WithTimeout(context.Background(), b.Timeout)
	defer cancel()
	return mgrclient.Client().Delete(ctx, obj, opt...)
}

func (b *Base) deleteAllOfPods(opts ...client.DeleteAllOfOption) error {
	ctx, cancel := context.WithTimeout(context.Background(), b.Timeout)
	defer cancel()
	obj := new(corev1.Pod)
	return mgrclient.Client().DeleteAllOf(ctx, obj, opts...)
}
